// @ts-nocheck
const { ESLint } = require('eslint');
const {readFileAsync} = require('../lib/fsUtil')
const path = require('path');
let eslint = null;

const ruleConfig = {
  unused: {
    fix: true,
    rules: {
      'unused-imports/no-unused-imports-ts': 'error',
      '@typescript-eslint/consistent-type-imports': 'error',
    },
  },
  importType: {
    fix: true,
    rules: {
      '@typescript-eslint/consistent-type-imports': 'error',
    },
  },
  components: {
    fix: false,
    rules: {
      '@chanjet/ban-import-from-modules': [
        'error',
        { target: /src\/(components|apphub|voucher-common)/, from: /src\/(modules|hkj)\// },
      ],
    },
  },
  'ban-this-in-arrowfunction': {
    fix: false,
    rules: {
      '@chanjet/ban-this-in-arrowfunction': 'error',
    },
  },
  apphub: {
    fix: false,
    rules: {
      '@chanjet/ban-import-from-modules': [
        'error',
        { target: /src\/(components|apphub|voucher-common)/, from: /src\/(modules|hkj)\// },
      ],
    },
  },
  
  hkj: {
    fix: false,
    rules: {
      '@chanjet/ban-import-from-modules': [
        'error',
        { target: /src\/hkj/, from: /src\/modules\// },
      ],
    },
  },
  'voucher-common': {
    fix: false,
    rules: {
      '@chanjet/ban-import-from-modules': [
        'error',
        { target: /src\/(components|apphub|voucher-common)/, from: /src\/(modules|hkj)\// },
      ],
    },
  },
};

/**
 * @param {string} filePath 
 * @param {object} opt 
 */
module.exports.transform = async function transform(filePath, opt) {
  if (eslint === null) {
    eslint = new ESLint(createConfig(ruleConfig[opt.type]));
  }
  // const results = await eslint.lintFiles([filePath]);
  let results = await eslint.lintText(await readFileAsync(filePath, {encoding: 'utf-8'}), {filePath});
  await ESLint.outputFixes(results);
  return results;
};

function createConfig(opt) {
  const CliDir = path.resolve(__dirname, '../');

  return {
    // 更改cwd, 让eslint 加载插件时，参考当前文件所在路径
    cwd: CliDir,
    allowInlineConfig: true,
    cache: true,
    errorOnUnmatchedPattern: true,
    extensions: ['.tsx', '.ts'],
    fix: opt.fix,
    fixTypes: undefined,
    ignore: true,
    ignorePath: undefined,
    overrideConfig: {
      env: undefined,
      globals: undefined,
      ignorePatterns: undefined,
      parser: '@typescript-eslint/parser',
      parserOptions: {},
      plugins: ['@chanjet/eslint-plugin', 'unused-imports', '@typescript-eslint'],
      rules: opt.rules,
    },
    // overrideConfigFile: clidir('.eslintrc.js'),
    reportUnusedDisableDirectives: undefined,
    resolvePluginsRelativeTo: undefined,
    useEslintrc: false,
  };
}
